import React, { Component } from 'react';
import {
  AppRegistry,
  Dimensions,
  Platform,
  NativeModules,
  DeviceInfo,
  StyleSheet,
  Image,
  Text,
  View,
  TextInput,
  PixelRatio,
  TouchableOpacity,
  ScrollView,
  FlatList,
  ActivityIndicator,
} from 'react-native';
var Common = require('./common');
var num = 1;//分页
const pixelRatio = PixelRatio.get();
const dismissKeyboard = require('dismissKeyboard');
// iPhoneX
const X_WIDTH = 375;
const X_HEIGHT = 812;

// screen
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;
export default class Search extends Component<Props> {
  static navigationOptions = {
      headerTitle: '搜索',
      tabBarLabel: '搜索',
  };
  constructor(props){
    super(props);
    this.state = {
      text:'',
      news:[],
      refreshing: false,//下拉刷新
			hasMore: true,//是否有更多数据
			endText: '加载更多...',

    };
  }
  isIphoneX() {

    return (

        Platform.OS === 'ios' && 

        ((SCREEN_HEIGHT === X_HEIGHT && SCREEN_WIDTH === X_WIDTH) || 

        (SCREEN_HEIGHT === X_WIDTH && SCREEN_WIDTH === X_HEIGHT))

    )

}


  ifIphoneX () {
    var flag = this.isIphoneX();
    if (flag) {
  console.log('true')
        this.setState({
          iphonex:true
        })
    } else {
  console.log('false')
        this.setState({
          iphonex:false
        })
    }
  }
  login(){
    var _this = this;
    Common.ajaxPost(Common.url + 'login.php', function(res){
      if(res.code == "0000"){

      }
    }.bind(this), {verify:'08login',t:''});
  }

  toRegister(){
    this.props.navigation.navigate('Register')
  }

  toBack(){
    this.props.navigation.goBack()
  }

  //http://118.123.13.251:8012/searchcar.php?action=search&searchword=奥迪&page=1&pagesize=10
  getData() {
		var _this = this;

		Common.ajaxGet(Common.url + 'searchcar.php?action=search&searchword='+ this.state.text +'&page=' + num + '&pagesize=10', function (res) {
			console.log(res)
			if (res.code == 1) {
				var data = res.data;
				if (data.list && data.list.length) {
					this.setState({
						news: this.state.news.concat(data.list),
						refreshing: false,
						hasMore: true,
					})

				} else {
					this.setState({
						hasMore: false,
						refreshing: false,
					})
					console.log('hasMore', this.state.hasMore);
				}
			}
		}.bind(this), {verify: '08login', t: ''});
	}

  toDetail(id) {
		this.props.navigation.navigate('BrandDetail', id)
	}

  renderNews(data) {
		console.log('renderNews', data);
		var _this = this;
		if (data != undefined) {
			return (
        <View key={data.item.aid}>
					<TouchableOpacity style={styles.subItem} onPress={_this.toDetail.bind(_this, data.item.aid)}>
						<Text style={styles.txt}>{data.item.subject}</Text>
						<Image style={{width:22,height:22,}} source={require('./images/jiantou.png')} />
					</TouchableOpacity>
				</View>

			);
		} else {
			return (
				<Text>空</Text>
			)
		}
	}

	keyExtractor = (item, index) => item.aid + '';//生成key
	refresh() {
		num = 1;
		this.setState({
			refreshing: true
		})
		this.getData();
	}

	loadMore() {
		console.log('loadMore');
		num++;

		console.log('hasMore', this.state.hasMore);
		if (this.state.hasMore) {
			this.getData();
		}
		else{
			this.setState({
				endText: '无更多数据'
			})
		}
	}

	renderFooter() {
		console.log('renderFooter');
		if(this.state.refreshing){
			return (
				<View style={{padding: 20}}>
					<ActivityIndicator/>
					<Text style={{textAlign: 'center'}}>{this.state.endText}</Text>
				</View>
			)
		}
		else{
			return (
				<View></View>
			)
		}
	}


  componentDidMount(){
    this.ifIphoneX();
    // console.log(this.props.navigation.state.params)
    // if(this.props.navigation.state.params.from){
    //   this.setState({
    //     from:this.props.navigation.state.params,
    //   })
    // }
  }
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <View style={styles.search}>
          <View style={styles.searchbox}>
            <Image style={{width:15,height:15,marginRight:10,marginLeft:10}} source={require('./images/sousuo.png')} />
            <TextInput
              style={styles.text}
              onChangeText={(text) => {
                this.setState({
                  text: text
                },()=>{this.getData()})
              }}
              placeholder='车型、颜色、价格...'
              placeholderTextColor='#d9d9d9'
            />
          </View>
          <TouchableOpacity onPress={this.toBack.bind(this)}>
            <Text style={{fontSize:14,marginLeft:14}}>取消</Text>
          </TouchableOpacity>

        </View>

          {this.state.news.length && this.state.text ? (
  					<FlatList
  						ListFooterComponent={this.renderFooter.bind(this)}
  						renderItem={this.renderNews.bind(this)}
  						data={this.state.news}
  						onEndReachedThreshold={0.2}
  						onEndReached={this.loadMore.bind(this)}
  						onRefresh={this.refresh.bind(this)}
  						refreshing={this.state.refreshing}
  						keyExtractor={this.keyExtractor.bind(this)}
  						style={{height: Common.screenHeight - 150}}
  					/>
  				) : (
            this.state.text?(
              <View
    						style={{alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff', marginTop: 5}}>
    						<Text style={[{
    							padding: 20,
    							width: Common.screenWidth,
    							textAlign: 'center',
    							fontSize: 16,
    							color: '#333'
    						}]}>无搜索结果</Text>
    					</View>
            ):(null)

  				)}
          {this.state.text?(null):(
            <View>
                <View style={styles.box}>
                  <Text style={{fontSize:14,color:'#444',paddingLeft:7,paddingBottom:15}}>热门搜索</Text>
                  <View style={styles.hot}>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                  </View>
                </View>
                <View style={styles.box}>
                  <Text style={{fontSize:14,color:'#444',paddingLeft:7,paddingBottom:15}}>猜你喜欢</Text>
                  <View style={styles.hot}>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.hotkey}>
                      <Text style={styles.hotkeytxt}>xxx</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              </View>
          )}

          </View>


    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    height:Common.screenHeight,
    backgroundColor: '#fff',
    position:'relative',
  },
  text:{},
  search:{
    flexDirection:'row',
    alignItems:'center',
    paddingLeft:14,
    paddingRight:14,
    paddingTop:10,
  },
  searchbox:{
    flexDirection:'row',
    alignItems:'center',
    borderColor:'#e9e9e9',
    borderWidth:1,
    borderRadius:20,
    flex:1,
    height:32,
  },
  box:{
    paddingTop:20,
    paddingLeft:7,
    paddingRight:7
  },
  hot:{
    flexDirection:'row',
    alignItems:'center',
    flexWrap:'wrap'
  },
  hotkey:{
    width:(Common.screenWidth-56)/3,
    marginLeft:7,
    marginRight:7,
    marginBottom:13,
    height:36,

    borderColor:'#e9e9e9',
    borderWidth:1

  },
  hotkeytxt:{
    fontSize:12,
    color:'#444',
    lineHeight:36,
    textAlign:'center',
  },
  subItem: {
		height: 36,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		borderBottomColor: '#e9e9e9',
		borderBottomWidth: 1,
		paddingLeft: 20,
		paddingRight: 20,
	},
	txt: {
		fontSize: 14,
		color: 'rgb(72,72,72)'
	}
});
